package goft

import "sync"

var once sync.Once
var Tasklist chan *TaskGroup

type Taskfun func(parm ...interface{})

type TaskGroup struct {
	f        Taskfun
	parm     []interface{}
	callBack func()
}

func init() {
	getTasklist()
	go func() {
		for i := range Tasklist {
			go func() {
				defer func() {
					if i.callBack != nil {
						i.callBack()
					}
				}()
				i.Exec()
			}()
		}
	}()
}

func NewTaskGroup(f Taskfun, b func(), parm ...interface{}) *TaskGroup {
	return &TaskGroup{f: f, callBack: b, parm: parm}
}

func (this *TaskGroup) Exec() {
	this.f(this.parm...)
}
func getTasklist() chan *TaskGroup {
	once.Do(func() {
		Tasklist = make(chan *TaskGroup)
	})
	return Tasklist
}

func Task(f Taskfun, b func(), parm ...interface{}) {
	if f == nil {
		return
	}
	go func() {
		getTasklist() <- NewTaskGroup(f, b, parm)
	}()
}
